package ball;

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class Mp3Encode implements Runnable {

	public String filename;
	public AudioInputStream stream;
	public SourceDataLine playLine;
	public AudioFormat baseFormat;
	public long currentByte = 0;
	public int numThread = 0;
	public int numBytesRead = -1;
	public int bufferSize;
	private FileInputStream in;

	public Mp3Encode(String name) {
		filename = name;	
	}
	
	private void getFormat(String filename) {
		try {
			stream = AudioSystem.getAudioInputStream(
					new File(filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
		baseFormat = stream.getFormat();
		int fIndex = filename.lastIndexOf(".");
		String extend = filename.substring(fIndex + 1);
		if ( extend.equalsIgnoreCase("wav") ) {
			baseFormat = decodingMusic(baseFormat);
		}		
	}

	private AudioFormat decodingMusic(AudioFormat format) {
		AudioFormat decodedFormat = new AudioFormat(
			AudioFormat.Encoding.PCM_SIGNED,
			format.getSampleRate(), format.getSampleSizeInBits(),
			format.getChannels(), format.getFrameSize(),
			format.getFrameRate(), format.isBigEndian()
		);
		return decodedFormat;
	}

	private SourceDataLine getLine(AudioFormat f) {
		RandomAccessFile source = null;
		try {
			source = new RandomAccessFile(filename, "r");
		} catch (Exception e) {
			e.printStackTrace();
		}
		SourceDataLine line = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class, f);
		bufferSize = baseFormat.getFrameSize() * Math.round(
				baseFormat.getSampleRate() / 10);
		byte[] buffer = new byte[bufferSize];
		try {
			line = (SourceDataLine)AudioSystem.getLine(info);
			line.open(f, bufferSize);
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
		line.start();

		try {
			if ( numBytesRead == -1 ) {
				currentByte = buffer.length;
				numBytesRead = 0;
			}
			source.seek(currentByte);
			while ( (numBytesRead != -1) ) {
				numBytesRead = source.read(buffer, 0, buffer.length);
				currentByte += numBytesRead;
				if ( numBytesRead != -1 ) {
					line.write(buffer, 0, numBytesRead);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return line;

	}
	
	public void run() {
		play();
	}

	public synchronized void play() {
		getFormat(filename);
		playLine = getLine(baseFormat);
		playLine.close();

	}


/*
 * 	public static void main(String args[]) {
		new Thread(new Mp3Encode("resource/bomb.wav")).start();
	}
       	*/

}
